package pearson.automation;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;

public class ScreenshotLogger extends TestListenerAdapter {
    
    private void makeScreenshot(ITestResult result) {
        Reporter.setCurrentTestResult(result);
        try {
            //Close <div> for previous step
            Reporter.log("</div><br>");
            
            //Make and save screenshot
            File f = ((TakesScreenshot) BasePearsonTest.browser.getDriver()).getScreenshotAs(OutputType.FILE);
            String screenshotName = String.format("%1$s/%2$s/%3$s/failure_%4$d.png", 
                "Screenshots",                          //Folder
                result.getTestClass().getRealClass().getSimpleName(),        //Class
                result.getName(),                        //Method
                result.getParameters().hashCode());     //Parameters signature
            
            File screenshot =  new File(screenshotName);
            FileUtils.copyFile(f, screenshot);
            
            //Add screenshot link to the file
            String hyperLink = String.format("../../artifact/%1$s", screenshotName);
            Reporter.log(String.format(
                    "<h3><b>Test failed </b> - <a href='%1$s'>Screenshot</a></h3>",
                        hyperLink));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void onTestFailure(ITestResult result) {
        makeScreenshot(result);
    }
    
    @Override
    public void onConfigurationFailure(ITestResult result) {
        makeScreenshot(result);
    }
}
